from apps.forms import BaseForm
from wtforms import  StringField
from wtforms.validators import regexp,InputRequired
import hashlib

class SMSCaptchaForm(BaseForm):
    salt = "q3423805gdflvbdfvhsdoa`#$%"
    telephone = StringField(validators=[regexp(r'1[3456789]\d{9}',message="手机号错误")])
    timestamp = StringField(validators=[regexp(r'\d{13}')])
    sign = StringField(validators=[InputRequired()])

    def validate(self):
        result = super(SMSCaptchaForm, self).validate()
        if not result:
            return False

        telephone = self.telephone.data
        timestamp = self.timestamp.data
        sign = self.sign.data
        # hashlib.md5生成的是的 md5的对象，需要使用hexdigest转换为md5的值
        sign2 = hashlib.md5((timestamp+telephone+self.salt).encode('utf-8')).hexdigest()
        # print("服务器端的sign2: %s" %sign2)
        # print("客户端生成的sign: %s" %sign)
        if sign == sign2:
            return True
        else:
            return False